package com.tangkun.environment.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.gongzuo.DepartmentAreaReturn;
import com.tangkun.environment.entity.login.DepartmentscopeIndexReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 附近污染源
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 */
public class LocationDemo extends BaseActivity implements SensorEventListener {
    @BindView(R.id.iv_qiyeguanli_left)
    ImageView ivQiyeguanliLeft;
    @BindView(R.id.tv_qiyeguanli_middle)
    TextView tvQiyeguanliMiddle;
    @BindView(R.id.iv_qiyeguanli_right)
    ImageView ivQiyeguanliRight;
    @BindView(R.id.tv_location_bottom_name)
    TextView tvLocationBottomName;
    @BindView(R.id.tv_location_bottom_distance_wuruanyuannum)
    TextView tvLocationBottomDistanceWuruanyuannum;
    @BindView(R.id.tv_location_bottom_beizhu)
    TextView tvLocationBottomBeizhu;
    @BindView(R.id.ll_location_bottom)
    LinearLayout llLocationBottom;

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00c27b;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    //纬度
    private double mCurrentLat = 0.0;
    //经度
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;

    MapView mMapView;
    BaiduMap mBaiduMap;

    // UI相关
    OnCheckedChangeListener radioButtonListener;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private float direction;

    private ItemizedOverlay itemizedOverlay;

    private boolean hasRequestedData = false;

    /**
     * 小于等于 13.5 显示区 1，区县；默认
     * 13.5 -<=15 显示街道 2，街道
     * 15 <= 16 显示 小区、 3、社区
     * 大于16 显示综合体  4
     */
    private int type = 4;

    /**
     * 社区ID
     */
    private String propertyid = "";
    /**
     * 社区lat
     */
    private String propertylat = "";
    /**
     * 社区lng
     */
    private String propertylng = "";
    /**
     * 社区名称
     */
    private String propertynames = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.bind(this);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        // 隐藏缩放按钮
        mMapView.showZoomControls(false);
        // 设置地图缩放范围5米和20公里
        mMapView.getMap().setMaxAndMinZoomLevel(21.0f, 11.0f);
        // 删除百度地图logo
        mMapView.removeViewAt(1);

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(30 * 1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

        //设置模式为
//        mCurrentMode = LocationMode.FOLLOWING;
        mCurrentMode = LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.overlook(0);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

        // 修改为自定义marker
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_ditu_dingweidian);
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker,
                getResources().getColor(R.color.transparent), getResources().getColor(R.color.common_green)));

        //对marker添加点击相应事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                //tangkun获取到定位后请求污染源
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("distance", "5000000");
                hashMap.put("lat", marker.getPosition().latitude + "");
                hashMap.put("lng", marker.getPosition().longitude + "");
                //获取子列表 type+1就获取到下一级列表
                if (type != 4) {
                    type++;
                    //缩放
                    LatLng ll = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    if (type == 2)
                        builder.target(ll).zoom(14.5f);
                    if (type == 3)
                        builder.target(ll).zoom(15.5f);
                    if (type == 4)
                        builder.target(ll).zoom(16.5f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    hashMap.put("type", type + "");
                    departmentArea(hashMap);
                } else {
                    //综合体
                    for (DepartmentAreaReturn.DataBean bean : dataList) {
                        LogUtils.e("bean.lat:" + bean.lat + "  marker.getPosition().latitude:" + marker.getPosition().latitude);
                        LogUtils.e("bean.lng:" + bean.lng + "  marker.getPosition().longitude:" + marker.getPosition().longitude);
                        if (bean.lat == marker.getPosition().latitude && bean.lng == marker.getPosition().longitude) {
                            llLocationBottom.setVisibility(View.VISIBLE);
                            //名称
                            if (!TextUtils.isEmpty(bean.names)) {
                                tvLocationBottomName.setText(bean.names);
                            } else {
                                tvLocationBottomName.setText("");
                            }
                            //距离
                            double lat = bean.lat;
                            double lng = bean.lng;
                            String myLat = SharePrefercesUtils.getLatitude(LocationDemo.this);
                            String myLng = SharePrefercesUtils.getLongitude(LocationDemo.this);
                            LatLng latLngStart = new LatLng(Double.valueOf(lat).doubleValue(), Double.valueOf(lng).doubleValue());
                            LatLng latLngEnd = new LatLng(Double.valueOf(myLat).doubleValue(), Double.valueOf(myLng).doubleValue());
                            //计算p1、p2两点之间的直线距离，单位：米
                            String distance = "";
                            if (DistanceUtil.getDistance(latLngStart, latLngEnd) > 1000) {
                                distance = Utils.getOneDecimalPoint(DistanceUtil.getDistance(latLngStart, latLngEnd) / 1000) + "km";
                            } else {
                                distance = Utils.getOneDecimalPoint(DistanceUtil.getDistance(latLngStart, latLngEnd)) + "m";
                            }
                            //距离和污染源数量
                            tvLocationBottomDistanceWuruanyuannum.setText("距您" + distance + " 共有污染源" + bean.enterprisenum + "个");
                            //备注
                            if (!TextUtils.isEmpty(bean.description)) {
                                tvLocationBottomBeizhu.setText(bean.description);
                            } else {
                                tvLocationBottomBeizhu.setText("");
                            }
                            //社区ID
                            propertyid = bean.ids;
                            //社区名称
                            propertynames = bean.names;
                            //lat
                            propertylat = bean.lat + "";
                            //lng
                            propertylng = bean.lng + "";
                        }
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @OnClick({R.id.iv_qiyeguanli_left, R.id.iv_qiyeguanli_right, R.id.ll_location_bottom})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_qiyeguanli_left:
                JumpHelper.finish(LocationDemo.this);
                break;
            case R.id.iv_qiyeguanli_right:
                JumpHelper.jump(LocationDemo.this, LocationDemo2.class, false);
                break;
            case R.id.ll_location_bottom://底部控件 社区
                Intent intent = new Intent(LocationDemo.this, ShequWuRanYuanActivity.class);
                intent.putExtra("id", propertyid);
                intent.putExtra("names", propertynames);
                intent.putExtra("lat", propertylat);
                intent.putExtra("lng", propertylng);
                JumpHelper.jump(LocationDemo.this, intent, false);
                break;
        }
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(13.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }

            if (!hasRequestedData) {
                //tangkun获取到定位后请求污染源
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("distance", "5000000");
                hashMap.put("lat", mCurrentLat + "");
                hashMap.put("lng", mCurrentLon + "");
                hashMap.put("type", type + "");
                departmentArea(hashMap);
            } else {
                initOverlay();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    /**
     * 污染源集合
     */
    private List<DepartmentAreaReturn.DataBean> dataList = new ArrayList<DepartmentAreaReturn.DataBean>();

    /**
     * 请求参数map 然后绘制到地图上去
     *
     * @param hashMap
     */
    private void departmentArea(HashMap<String, String> hashMap) {
        fromNetwork.departmentArea(hashMap).compose(new RxActivityHelper<DepartmentAreaReturn>().ioMain(LocationDemo.this, false))
                .subscribe(new MySubscribe<DepartmentAreaReturn>(LocationDemo.this, false) {
                    @Override
                    protected void success(DepartmentAreaReturn resultBean) {
                        hasRequestedData = true;
                        if (resultBean.data != null) {
                            dataList.clear();
                            dataList.addAll(resultBean.data);
                            initOverlay();
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        hasRequestedData = true;
                        showToast(errorMessage + "");
                    }
                });
    }

    /**
     * 绘制覆盖物
     */
    public void initOverlay() {
        //清除所有Overlay
        mBaiduMap.clear();

        //地图区域范围  添加多边形
        List<DepartmentscopeIndexReturn.DataBean> dataBeanList = Session.getInstance().getDepartmentscopeIndexReturn();
        if (dataBeanList != null) {
            for (DepartmentscopeIndexReturn.DataBean dataBean : dataBeanList) {
                //当前type为4 展示type为2的坐标图形
                if (dataBean.type.equals("2")) {
                    List<DepartmentscopeIndexReturn.DataBean.DataItemBean> dataItemBeanList = dataBean.data;
                    if (dataItemBeanList != null) {
                        List<LatLng> latLngList = new ArrayList<LatLng>();
                        for (int i = 0; i < dataItemBeanList.size(); i++) {
                            double latitude = Double.valueOf(dataItemBeanList.get(i).lat).doubleValue();
                            double longitude = Double.valueOf(dataItemBeanList.get(i).lng).doubleValue();
                            LatLng latLng = new LatLng(latitude, longitude);
                            latLngList.add(latLng);
                        }
                        OverlayOptions overLayOptions = new PolygonOptions().points(latLngList)
                                .stroke(new Stroke(3, 0xFF00c27b)).fillColor(0x3200c27b);
                        mBaiduMap.addOverlay(overLayOptions);
                    }
                }
            }
        }

        //添加覆盖物区县、社区、街道
        if (dataList == null) {
            return;
        }
        //添加覆盖物区县、社区、街道
        for (int i = 0; i < dataList.size(); i++) {
            double lat = 0;
            double lng = 0;
            try {
                lat = Double.valueOf(dataList.get(i).lat).doubleValue();
                lng = Double.valueOf(dataList.get(i).lng).doubleValue();
            } catch (Exception e) {
                lat = 0;
                lng = 0;
            }
            LatLng latLng = new LatLng(lat, lng);
            View view = LayoutInflater.from(this).inflate(R.layout.pupopwindow_not_shequ, null);
            //区、街道、小区控件
            LinearLayout ll1 = (LinearLayout) view.findViewById(R.id.ll_ditu1);
            TextView up1Tv = (TextView) view.findViewById(R.id.tv_ditu1_up);
            TextView down1Tv = (TextView) view.findViewById(R.id.tv_ditu1_down);

            //综合体控件
            LinearLayout ll2 = (LinearLayout) view.findViewById(R.id.ll_ditu2);
            TextView up2Tv = (TextView) view.findViewById(R.id.tv_ditu2_up);
            //名称
            String names = "";
            if (!TextUtils.isEmpty(dataList.get(i).names)) {
                names = dataList.get(i).names;
            } else {
                names = "";
            }
            switch (type) {
                case 1://区县
                    ll1.setVisibility(View.VISIBLE);
                    ll2.setVisibility(View.GONE);
                    up1Tv.setText(names);
                    down1Tv.setText(dataList.get(i).streetnum + "街道、" + dataList.get(i).communitynum + "社区、" + dataList.get(i).enterprisenum + "污染源");
                    break;
                case 2://街道
                    ll1.setVisibility(View.VISIBLE);
                    ll2.setVisibility(View.GONE);
                    up1Tv.setText(names);
                    down1Tv.setText(dataList.get(i).communitynum + "社区、" + dataList.get(i).enterprisenum + "污染源");
                    break;
                case 3://社区
                    ll1.setVisibility(View.VISIBLE);
                    ll2.setVisibility(View.GONE);
                    up1Tv.setText(names);
                    down1Tv.setText(dataList.get(i).enterprisenum + "污染源");
                    break;
                case 4://综合体
                    ll1.setVisibility(View.GONE);
                    ll2.setVisibility(View.VISIBLE);
                    up2Tv.setText(names);
                    break;
            }

            Bitmap bitmap = getViewBitmap(view);
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                    .fromBitmap(bitmap);
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmapDescriptor)
                    .zIndex(9).draggable(true);
            Marker marker = (Marker) (mBaiduMap.addOverlay(markerOptions));

//            View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_data_infomation_shaixuan, null);
////            Button button = new Button(getApplicationContext());
//            InfoWindow.OnInfoWindowClickListener listener = null;
//
//            listener = new InfoWindow.OnInfoWindowClickListener() {
//                public void onInfoWindowClick() {
//                    LatLng ll = marker.getPosition();
////                    LatLng llNew = new LatLng(ll.latitude + 0.005,
////                            ll.longitude + 0.005);
////                    marker.setPosition(llNew);
////                    mBaiduMap.hideInfoWindow();
//                }
//            };
//            LatLng ll = marker.getPosition();
//            InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), ll, -47, listener);
//            mBaiduMap.showInfoWindow(mInfoWindow);
        }
    }

    /**
     * 将View转换成Bitmap
     *
     * @param addViewContent
     * @return
     */

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }


    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
}
